#include "d_Camera.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
#include <math.h>

d_Camera::d_Camera()
{
	is_light=false;
	pos[0]=pos[1]=pos[2]=0;
	dir[0]=dir[1]=0;
	dir[2]=1;
	up[0]=up[2]=0;
	up[1]=1;
}

void d_Camera::setDimensions(int w, int h)
{
	dimensions[0]=w;
	dimensions[1]=h;
}

void d_Camera::setViewport(int x, int y, int w, int h)
{
	viewport[0] = x;
	viewport[1] = y;
	viewport[2] = w;
	viewport[3] = h;
	perspective[1] = (double) w/ (double) h;
}

void d_Camera::setPerspective(double fovy)
{
	perspective[0] = fovy;
}

void d_Camera::setPosition(double x, double y, double z)
{
	pos[0] = x;
	pos[1] = y;
	pos[2] = z;
}

void d_Camera::setUpDirection(double x, double y, double z)
{
	up[0] = x;
	up[1] = y;
	up[2] = z;
}

void d_Camera::setDirection(double x, double y, double z)
{
	dir[0] = x;
	dir[1] = y;
	dir[2] = z;
}

void d_Camera::applyViewport()
{
	glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);
}

void d_Camera::applyPerspective()
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(perspective[0], perspective[1], 0.1, 100000);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void d_Camera::applyOrthographic()
{
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0,dimensions[0], 0, dimensions[1], 0.1, 1000000);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void d_Camera::resetPerspective()
{
    glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}

void d_Camera::applyModelview()
{
	gluLookAt(pos[0],pos[1],pos[2],
			  pos[0]+dir[0],pos[1]+dir[1],pos[2]+dir[2],
			  up[0],up[1],up[2]);
	if(is_light)
	{
		light->setPosition(pos[0],pos[1],pos[2], 1.0);
		light->applyProperties();
	}
}

void d_Camera::addLight(GLint gl_light)
{
	light = new d_Light(gl_light);
	light->setAmbient(0.2, 0.2, 0.2, 1.0);
	light->setDiffuse(0.2, 0.2, 0.2, 1.0);
	//light->setSpecular(0.2, 0.2, 0.2, 1.0);
	light->setPosition(pos[0],pos[1],pos[2],1.0);
	light->applyProperties();
	is_light = true;
}

void d_Camera::mouseClick(int button, int x, int y)
{
	start_click[0] = x;
	start_click[1] = y;
	button_state = button;
	switch(button)
	{
	//case LEFT:
	//case MIDDLE:
	//case RIGHT:
	}
}

void d_Camera::mouseDrag(int x, int y)
{
	switch(button_state)
	{
	case D_RIGHT:
		zoom(y);
	}
}

void d_Camera::zoom(int y)
{
	int cy = y-start_click[1];
	double scale = (double)cy/(double)viewport[3];
	pos = pos*exp(scale);
	//applyModelview();
}

void d_Camera::setDrag(int x, int y)
{
	last_pos[0] = x;
	last_pos[1] = y;
}

void d_Camera::applyDrag(int x, int y)
{
	//int xrel = x-last_pos[0];
	//std::cout << dir[0] << " , " << dir[2] << std::endl;
	//pos = pos.rotateByAxis(xrel*0.001, d_Vec3f(0,1,0));
	//dir = d_Vec3f(0,0,0)-norm(pos);//dir.rotateByAxis(xrel*0.001, d_Vector3D(0,1,0));
	//std::cout << xrel << std::endl;
	//last_pos[0] = x;
	//applyModelview();
}

